

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../sample/configure/constants.dart';
import '../../tgpage/device/firmware.dart';
import '../../tgpage/device/share.dart';
import '../../tgpage/event/event.dart';
import '../../tgpage/media/cloud_replay.dart';
import '../../tgpage/media/live.dart';
import '../../tgpage/media/local_replay.dart';
import '../../theme.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/rounded_image.dart';

/// 探鸽首页操作页面 - 未启用
Widget homeDeviceCard(Primary primary, Map<String, OnlineStatus> onlineStatusMap, Map<String, Thumbnail> thumbnailsMap,
    Map<String, BatteryStatus> batteryStatusMap, BuildContext context, VoidCallback onRemovedCallback) {
  return LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
      double width = constraints.maxWidth;
      double height = width * 9 / 16;

      return Column(
        children: [
          _wrapCardTopWithInkWell(primary, _buildCardTop(context, width, height, primary, thumbnailsMap, onlineStatusMap, batteryStatusMap),
              onlineStatusMap, context, onRemovedCallback),
          // 工具栏
          _buildCardBottom(context, primary, onRemovedCallback),
        ],
      );
    },
  );
}

Container _buildCardBottom(BuildContext context, Primary primary, VoidCallback onRemovedCallback) {
  return Container(
    height: 50,
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: _createBottomRadiusBorder(),
    ),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        _buildCardEventBtn(context, primary.deviceId ?? ""),
        _buildShareBtn(context, primary),
        _buildCardStoragePlaybackBtn(context, primary),
        _buildCardCloudPlaybackBtn(context, primary),
        _buildCardEditNameBtn(context, primary, onRemovedCallback),
      ],
    ),
  );
}

int recognizedCameraCount(Primary primary) {
  int cameraCount = 1;
  if (primary.deviceAttributes?.contains("ipc-2ch") == true) {
    cameraCount = 2;
  } else if (primary.deviceAbilities?.contains("3-composed") == true) {
    cameraCount = 3;
  }
  return cameraCount;
}

void _handleOnTap(Primary primary, Map<String, OnlineStatus> onlineStatusMap, BuildContext context) {

  // 有设备id  并且在线   就跳转

  final online = onlineStatusMap[primary.deviceId ?? ""]?.isOnline ?? false;
  if (!online) {
    SnackTips.show(context, "设备当前不在线！");
  } else {
    if (context.mounted) {
      int cameraCount = recognizedCameraCount(primary);
      LogUtils.e("cameraCount${cameraCount}");
      LogUtils.e("");
      final live = LivePage(
        deviceId: primary.deviceId ?? "",
        deviceName: primary.deviceName ?? "",
        cameraCount: cameraCount,
        lan: false,
      );

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => live),
      );
    }
  }
}

InkWell _wrapCardTopWithInkWell(
    Primary primary, Widget widget, Map<String, OnlineStatus> onlineStatusMap, BuildContext context, VoidCallback onRemovedCallback) {
  return InkWell(
    onTap: () => _handleOnTap(primary, onlineStatusMap, context),
    onLongPress: () => _handleOnLongPress(primary, context, onRemovedCallback),
    child: widget,
  );
}

void _handleOnLongPress(Primary primary, BuildContext pageContext, VoidCallback onRemovedCallback) {
  final isOwner = primary.isOwner ?? false;
  showDialog(
    context: pageContext,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('移除设备'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(isOwner ? '你确定要删除这个设备吗？' : "你确定要退出分享吗？"),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('取消'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            child: const Text('确定'),
            onPressed: () async {
              _removeDevice(primary, pageContext, onRemovedCallback);
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

void _removeDevice(Primary primary, BuildContext context, VoidCallback onRemovedCallback) async {
  final isOwner = primary.isOwner ?? false;
  if (isOwner) {
    final resp = await BindingService.unbind(primary.deviceId ?? "");
    if (!context.mounted) return;
    if (resp.success) {
      SnackTips.show(context, "设备已删除");
      onRemovedCallback.call();
    } else {
      SnackTips.show(context, "错误: ${resp.code} ${resp.message}");
    }
  } else {
    final resp = await SharingService.leaveSharing(primary.deviceId ?? "");
    if (!context.mounted) return;
    if (resp.success) {
      SnackTips.show(context, "已退出分享");
      onRemovedCallback.call();
    } else {
      SnackTips.show(context, "错误: ${resp.code} ${resp.message}");
    }
  }
}

SizedBox _buildCardTop(BuildContext context, double width, double height, Primary primary, Map<String, Thumbnail> thumbnailsMap,
    Map<String, OnlineStatus> onlineStatusMap, Map<String, BatteryStatus> batteryStatusMap) {
  return SizedBox(
      width: width,
      height: height,
      child: ClipRRect(
        borderRadius: _createTopRadiusBorder(),
        child: _buildCardContent(context, primary, thumbnailsMap, onlineStatusMap, batteryStatusMap),
      ));
}

Stack _buildCardContent(BuildContext context, Primary primary, Map<String, Thumbnail> thumbnailsMap, Map<String, OnlineStatus> onlineStatusMap,
    Map<String, BatteryStatus> batteryStatusMap) {
  return Stack(
    children: [
      _buildCardCover(primary, thumbnailsMap),
      _buildOnlineStatusOverlay(primary, onlineStatusMap),
      _buildCardOverlay(primary),
      if (SampleConstants.fullAbilitiesMode && primary.isOwner != true) homeCardShareLabel(),
      if (SampleConstants.fullAbilitiesMode)
        if (primary.isOwner == true) homeCardFirmwareUpgrade(context, primary.deviceId ?? ""),
      _buildBatteryIndicator(primary, batteryStatusMap),
    ],
  );
}

Positioned homeCardShareLabel() {
  return Positioned(
    right: 16,
    top: 16,
    child: Container(
      decoration: BoxDecoration(
        color: SampleThemeConfigure.colorPrimary,
        borderRadius: BorderRadius.circular(50.0),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 4),
      child: const Text(
        '来自分享',
        style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
      ),
    ),
  );
}

Positioned homeCardFirmwareUpgrade(BuildContext context, String deviceId) {
  return Positioned(
    left: 3,
    bottom: 3,
    child: Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(50.0),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 30,
            offset: const Offset(1, 1),
          ),
        ],
      ),
      child: IconButton(
        icon: const Icon(
          Icons.upload,
          size: 30.0,
          color: Colors.white,
        ),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => FirmwarePage(
                deviceId: deviceId,
              ),
            ),
          );
        },
      ),
    ),
  );
}

InkWell _buildShareBtn(BuildContext context, Primary primary) {
  return InkWell(
    onTap: () {
      if (primary.isOwner != true) {
        SnackTips.show(context, "只有设备主人才能管理共享！");
        return;
      }

      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SharePage(
            deviceId: primary.deviceId ?? "",
            deviceName: primary.deviceName ?? "",
          ),
        ),
      );
    },
    child: const Icon(Icons.share_rounded, size: 24, color: SampleThemeConfigure.colorPrimary),
  );
}

InkWell _buildCardEventBtn(BuildContext context, String deviceId) {
  return InkWell(
    onTap: () {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => EventPage(
            deviceId: deviceId,
          ),
        ),
      );
    },
    child: const Icon(Icons.event_note_rounded, size: 24, color: SampleThemeConfigure.colorPrimary),
  );
}

InkWell _buildCardCloudPlaybackBtn(BuildContext context, Primary primary) {
  return InkWell(
    onTap: () {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => CloudReplayPage(
              deviceId: primary.deviceId ?? "",
              deviceName: primary.deviceName ?? "",
            )),
      );
    },
    child: const Icon(Icons.wb_cloudy_rounded, size: 24, color: SampleThemeConfigure.colorPrimary),
  );
}

InkWell _buildCardEditNameBtn(BuildContext context, Primary primary, VoidCallback onRemovedCallback) {
  return InkWell(
    onTap: () async => _onEditDeviceName(context, primary.deviceId ?? "", onRemovedCallback),
    child: const Icon(Icons.mode_edit_rounded, size: 24, color: SampleThemeConfigure.colorPrimary),
  );
}

void _onEditDeviceName(BuildContext context, String deviceId, VoidCallback onRemovedCallback) {
  final TextEditingController controller = TextEditingController();

  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('更新名称'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            hintText: '新的名称，如"大门口"',
          ),
        ),
        actions: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              if (controller.text.isEmpty) {
                showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      content: const Text('设备名称不能为空'),
                      actions: <Widget>[
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text('确定'),
                        ),
                      ],
                    );
                  },
                );
              } else {
                final response = await SpecService.rename(deviceId, controller.text);
                if (!context.mounted) return;
                if (!response.success) {
                  SnackTips.show(context, "Error: ${response.message}");
                } else {
                  SnackTips.show(context, "重命名成功");
                  onRemovedCallback.call();
                }
                Navigator.of(context).pop();
              }
            },
            child: const Text('确认'),
          ),
        ],
      );
    },
  );
}

InkWell _buildCardStoragePlaybackBtn(BuildContext context, Primary primary) {
  return InkWell(
    onTap: () {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => LocalReplayPage(
              deviceId: primary.deviceId ?? "",
              deviceName: primary.deviceName ?? "",
            )),
      );
    },
    child: const Icon(Icons.sd_card_outlined, size: 24, color: SampleThemeConfigure.colorPrimary),
  );
}

BorderRadius _createBottomRadiusBorder() {
  return const BorderRadius.only(
    topLeft: Radius.circular(0),
    topRight: Radius.circular(0),
    bottomLeft: Radius.circular(10),
    bottomRight: Radius.circular(10),
  );
}

BorderRadius _createTopRadiusBorder() {
  return const BorderRadius.only(
    topLeft: Radius.circular(10),
    topRight: Radius.circular(10),
    bottomLeft: Radius.circular(0),
    bottomRight: Radius.circular(0),
  );
}

Positioned _buildCardCover(Primary primary, Map<String, Thumbnail> thumbnailsMap) {
  String url = "";
  if (thumbnailsMap.containsKey(primary.deviceId ?? "")) {
    url = thumbnailsMap[primary.deviceId ?? ""]?.url ?? "";
  }

  if (url.isEmpty) {
    return const Positioned.fill(
        child: RoundedNetworkImage(
          imageUrl: 'https://th.wallhaven.cc/small/we/werdv6.jpg',
        ));
  }

  return Positioned.fill(
      child: RoundedNetworkImage(
        imageUrl: url,
      ));
}

Widget _buildBatteryIndicator(Primary primary, Map<String, BatteryStatus> batteryStatusMap) {
  bool hasBattery = false;
  int level = -1;
  bool low = false;
  bool charing = false;
  if (batteryStatusMap.containsKey(primary.deviceId)) {
    level = batteryStatusMap[primary.deviceId]?.level ?? 0;
    low = batteryStatusMap[primary.deviceId]?.isLow ?? false;
    charing = batteryStatusMap[primary.deviceId]?.isCharging ?? false;
    if (level >= 0) {
      hasBattery = true;
    }
  }

  if (!hasBattery) {
    return Container();
  }

  final batteryLevel = '$level%';

  final Icon batteryIcon;
  if (charing) {
    batteryIcon = const Icon(
      size: 20,
      Icons.battery_charging_full_rounded,
      color: Colors.yellowAccent,
    );
  } else if (low) {
    batteryIcon = const Icon(
      size: 20,
      Icons.battery_1_bar,
      color: Colors.red,
    );
  } else {
    batteryIcon = const Icon(
      size: 20,
      Icons.battery_full,
      color: Colors.white,
    );
  }

  return Positioned(
    right: 16,
    bottom: 16,
    child: Row(
      children: [
        batteryIcon,
        const SizedBox(width: 1),
        Text(
          batteryLevel,
          style: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    ),
  );
}

Widget _buildCardOverlay(Primary primary) {
  return Positioned.fill(
      child: Container(
        padding: const EdgeInsets.all(16.0),
        decoration: _createLinearGradientDecoration(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[buildCardOverlayTop(primary)],
        ),
      ));
}

Widget _buildOnlineStatusOverlay(Primary primary, Map<String, OnlineStatus> onlineStatusMap) {
  bool online = false;
  int offlineTime = 0;
  if (onlineStatusMap.containsKey(primary.deviceId ?? "")) {
    online = onlineStatusMap[primary.deviceId ?? ""]?.isOnline ?? false;
    offlineTime = onlineStatusMap[primary.deviceId ?? ""]?.offlineAt ?? 0;
  }

  if (online) {
    return Container();
  }

  return Positioned.fill(
    child: Container(
      color: Colors.black54, // 半透明黑色背景
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Icon(
              Icons.cloud_off,
              size: 30,
              color: Colors.white,
            ),
            const SizedBox(height: 8),
            const Text(
              '设备已离线',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              '离线时间为 ${offlineTime.secondToFormattedDate()}',
              style: const TextStyle(
                color: Colors.white70,
                fontSize: 10,
              ),
            ),
          ],
        ),
      ),
    ),
  );
}

BoxDecoration _createLinearGradientDecoration() {
  return BoxDecoration(
    gradient: LinearGradient(
      begin: Alignment.topCenter,
      end: Alignment.bottomCenter,
      colors: [Colors.black.withOpacity(0.6), Colors.transparent],
      stops: const [
        0.0,
        0.5,
      ],
    ),
  );
}

Widget buildCardOverlayTop(Primary primary) {
  return Row(
    children: <Widget>[
      const Icon(
        Icons.videocam_rounded,
        color: Colors.white,
        size: 30,
      ),
      const SizedBox(width: 8.0),
      Text(
        primary.deviceName ?? "",
        style: const TextStyle(fontSize: 18.0, color: Colors.white),
      ),
    ],
  );
}
